package com.ethanzzh.security.ethanzzhdemo.security;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

//自定义用户逻辑
//用户信息的获取逻辑 在SpringSecurity被封装在UserDetailsService里面
@Component
public class MyUserDetailsService implements UserDetailsService, SocialUserDetailsService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    //loadUserByUsername作用是通过你登录时入的用户名去读取一下用户信息，用户信息被封装在UserDetails接口的实现类里面
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        logger.info("用户登录用户名：" + username);
        return buildUser(username);

    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {

        logger.info("社交登录用户名：" + userId);
        return buildUser(userId);


    }

    private SocialUserDetails buildUser(String userId) {

        //根据用户名查找用户 user

        //根据查找到的用户信息判断用户是否被冻结

        //passwordEncoder.encode("123456") 这个是在注册的时候做的，注册成功后
        //passwordEncoder.encode("123456") 返回的密码会存在数据库， 通过调用那个密码来作为password



        String password = passwordEncoder.encode("123456");
        logger.info("数据库密码是：" + password);
        return new SocialUser(userId, password,
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER"));
    }
}
